Yes. To construct an object, there must be a constructor.
Here is where the constructor is used in the main()
method:
HelloObject anObject = new HelloObject(); // 2. a HelloObject
// is created.
But here is the class definition of HelloObject
:
class HelloObject { void speak() { System.out.println("Hello from an object!"); } }
There is no constructor described in the class definition. This is OK. A class will have a constructor even if one is not explicitly included in the class definition. If the class definition does not include a constructor a default constructor is automatically supplied by the Java compiler.
The class definition of HelloObject
does not include a constructor.
But the compiler does something like this:
class HelloObject
{
HelloObject() // default constructor
{
}
void speak()
{
System.out.println("Hello from an object!");
}
}